package cm.unit3.theme3;

public class ReOrderArray {
    public int[] reOrderArray (int[] array){
        int []newArray = new int[array.length];
        int splitPoint = 0;
        for (int j : array) {
            if ((j & 0x1) != 0) {
                splitPoint++;
            }
        }

        int right = splitPoint;
        int left = 0;
        for (int j : array) {
            if ((j & 0x1) != 0) {
                newArray[left++] = j;
            } else {
                newArray[right++] = j;
            }
        }
        return newArray;
    }

    // 和上面不是同一道题
    public int[] reOrderArray01 (int[] array) {
        // 双指针
        int left = 0;
        int right = array.length - 1;
        int temp = 0;
        while (left<right){
            // 如果左边是奇数;遇到一个偶数或越界停止
            while ( left<array.length && (array[left]&0x1)!=0 ){
                left++;
            }

            // 如果右边是偶数;遇到一个奇数或越界停止
            while ( right>=0 && (array[right]&0x1)==0){
                right--;
            }

            // 交换奇数偶数并移动指针
            if (left<array.length && right>=0){
                temp = array[left];
                array[left++] = array[right];
                array[right--] = temp;
            }

        }
        return array;
    }
}
